var _controller = CTX + '/sys/dept';
var _exportList = _controller + '/export';
var Req = {
    list: {method: 'GET', url: _controller},
    add: {method: 'POST', url: _controller},
    update: {method: 'PUT', url: _controller},
    del: {method: 'DELETE', url: _controller}
};

var deptMap = {};

var $grid = null;
var $dlg = null;

$(function () {
    $grid = $('#deptGrid');
    $dlg = $('#dlg');

    initDeptTreeGrid();

    $('#searchBtn').click(searchGrid);

    $('#resetBtn').click(function () {
        $('#searchForm').form('reset');
        $('#searchBtn').trigger('click');
    });
});

function getQueryParams() {
    var params = $('#searchForm').serializeForm();
    return params;
}

function initDeptTreeGrid() {
    $grid.treegrid({
        fit: true,
        fitColumns: true,
        idField: 'id',
        treeField: 'name',
        method: Req.list.method,
        url: Req.list.url,
        queryParams: getQueryParams(),
        columns: [[{
            field: '_opts_',
            title: '操作',
            width: 30,
            align: 'center',
            formatter: function (v, row) {//  没有index
                var ary = [];
                ary.push('<a href="javascript:;" permission="sys:dept:updage" class="row-btn" title="修改" onclick="update(\'' + row.id + '\')"><i class=" fa fa-edit"></i></a>');
                ary.push('<a href="javascript:;" permission="sys:dept:del" class="row-btn" title="删除" onclick="deletes(\'' + row.id + '\')"><i class="fa fa-trash"></i></a>');
                return ary.join('&nbsp;<span class="btn-separator"></span>&nbsp;');
            }
        }, {
            field: 'id',
            title: '部门ID',
            width: 100
        }, {
            field: 'name',
            title: '名称',
            width: 100,
            formatter: function (v, row) {
                return '<a href="javascript:;" class="row-btn" onclick="see(\'' + row.id + '\')">' + v + '</a>';
            }
        }, {
            field: 'parentId',
            title: '父部门',
            width: 100,
            formatter: function (v, row) {
                if (v == 0) {
                    return '';
                }
                var dept = deptMap[v];
                if (dept && dept.id == v) {
                    return dept.name;
                }
                return v;
            }
        }, {
            field: 'seq',
            title: '顺序',
            width: 30
        }, {
            field: 'remark',
            title: '备注',
            width: 150
        }]],
        loadFilter: function (data, parentId) {
            if (data.data) {
                var gridData = data.data;
                refreshParentId(gridData);
                return gridData;
            } else {
                return data;
            }
        },
        onLoadSuccess: function (row, data) {
            $.app.controlPermission();
            // 执行一次
            $grid.treegrid('collapseAll');
        },
        onContextMenu: function (e, row) {
            e.preventDefault();
            $grid.treegrid('select', row.id);
            $('#cm').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
        }
    });

}

function searchGrid() {
    $grid.treegrid('load', getQueryParams());
}

/**
 * 新增、修改、删除后以及刷新tree grid表格前，刷新父部门信息（列表、表单）
 * @param treeGridData 包含全部部门信息
 */
function refreshParentId(treeGridData) {
    if (!treeGridData) {
        treeGridData = $grid.treegrid('getData');
    }
    // 将tree grid数据转换为 id-name的map数据，用于treegrid列表
    changeTreeGrid2Map(treeGridData, 'id', 'name', 'children', deptMap);
    // 将tree grid结构处理成easyui tree可用的数据，构造combotree
    var treeData = changeTreeGrid2TreeData(treeGridData, 'id', 'name', 'children');
    treeData = e_tree_addall_filter(treeData, {id: 0, text: '', selected: true});
    $('#fm_parentId').combotree({
        data: treeData,
        value: 0
    });
}

function add() {
    var $form = $dlg.find('form');
    $form.form('reset');

    $dlg.dialog({
        title: '新增部门',
        modal: true,
        inline: true,
        buttons: [{
            text: '确定',
            iconCls: 'e-icon fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(Req.add, formObj, function (id) {
                    // searchGrid();
                    formObj.id = id;
                    addTreeGridRow(formObj);
                    refreshParentId();
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function addSameLevel() {
    add();
    var row = $grid.treegrid('getSelections')[0];
    var parent = $grid.treegrid('getParent', row.id);
    // 选择根节点（系统管理）时，parent不存在
    if (parent) {
        $dlg.find('form').form('load', {parentId: parent.id});
    } else {
        // 顶级节点的parent id===0
        $dlg.find('form').form('load', {parentId: 0});
    }
}

function addDownLevel() {
    add();
    var row = $grid.treegrid('getSelections')[0];
    $dlg.find('form').form('load', {parentId: row.id});
}

// 针对行内触发和非行内触发两种情况
function update(id) {
    var row = null;
    if (id || id === 0) {// 考虑到存在id===0的情况
        row = deptMap[id];
    } else {
        row = $grid.treegrid('getSelections')[0];
    }
    if (!row) {
        $.showMsg('请选择一行数据！');
        return;
    }

    var $form = $dlg.find('form');
    $form.form('load', row);
    $dlg.dialog({
        title: '修改部门',
        modal: true,
        buttons: [{
            text: '确定',
            iconCls: 'fa fa-save',
            plain: true,
            handler: function () {
                // searchGrid();
                var formObj = $form.serializeForm();
                $form.submitEForm(Req.update, formObj, function (id) {
                    if (row.parentId == formObj.parentId) {
                        // 更新当前行
                        $grid.treegrid('update', {
                            id: row.id,
                            row: formObj
                        });
                    } else {
                        $grid.treegrid('remove', row.id);
                        if (row.children) {
                            formObj.children = row.children;
                        }
                        addTreeGridRow(formObj);
                    }
                    refreshParentId();
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

// 针对行内触发的情况
function see(id) {
    var row = deptMap[id];

    $dlg.find('form').form('load', row);
    $dlg.dialog({
        title: '查看部门',
        modal: true,
        buttons: [{
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

// 针对行内触发和非行内触发两种情况
function deletes(id) {
    if (id || id === 0) {// 考虑到存在id===0的情况
        var row = deptMap[id];
        $.confirmMsg('确定要删除部门[' + row.name + ']吗？', function () {
            doDelete([row.id]);
        });
    } else {
        var rows = $grid.treegrid('getSelections'), ids = [];
        if (rows && rows.length) {
            $.each(rows, function (i, row) {
                ids.push(row.id);
            });
            $.confirmMsg('确定要删除选择的[' + ids.length + ']条记录？', function () {
                doDelete(ids);
            });
        } else {
            $.showMsg('请选择要删除的记录');
        }
    }
}

function doDelete(ids) {
    $.ajax({
        type: Req.del.method,
        url: Req.del.url,
        data: {
            ids: ids.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result, function (data) {
                // $dataGrid.treegrid('reload');
                $.each(ids, function (i, id) {
                    $grid.treegrid('remove', id);
                });
                refreshParentId();
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}

/**
 * 向tree grid 中添加一行，并排序
 * @param rowData
 */
function addTreeGridRow(rowData) {
    var parentId = rowData.parentId;
    // 1.获取添加行父节点下的同级数据
    var children = [];
    if (rowData.root) {
        children = $grid.treegrid('getRoots');
    } else {
        children = $grid.treegrid('getChildren', parentId);
    }

    var filterChildren = $.grep(children, function (child, i) {
        return child.parentId === parentId;
    });

    // 2.删除添加行父节点下的同级行信息
    if (rowData.root) {
        $grid.treegrid('loadData', []);
    } else {
        $.each(filterChildren, function (i, c) {
            $grid.treegrid('remove', c.id);
        });
    }

    // 3.同级数据中加入新添加行并排序
    filterChildren.push(rowData);
    filterChildren.sort(function (a, b) {
        return a.seq - b.seq;
    });

    // 4.将排序后的同级数据添加到父节点下
    $grid.treegrid('append', {
        parent: parentId,
        data: filterChildren
    });
}
